﻿using System;

namespace DotNetStar.TheKing.Domain.EventHandlers
{
    using DotNetStar.TheKing.Infrastructure;
    using Microsoft.Extensions.Caching.Memory;
    using Microsoft.Extensions.Logging;
    using SDDP;

    /// <summary>
    /// 用户积分事件处理。
    /// </summary>
    /// <seealso cref="SDDP.IEventHandler{DotNetStar.TheKing.Domain.Events.UserPointEvent}" />
    public class UserPointEventHandler : EventHandlerBase<UserPointEventHandler>, IEventHandler<UserPointEvent>
    {
        private IStorage<User,long> _userStorage;
        private IStorage<PointsStrategy,string> _pointStrategyStorage;
        private IStorage<UserPointHistory, Guid> _userPointListStorage;

        public UserPointEventHandler(IStorage<User, long> userStorage,
            IStorage<PointsStrategy, string> pointStrategyStorage,
            IStorage<UserPointHistory, Guid> userPointListStorage,
            IMemoryCache memoryCache,
            ILoggerFactory loggerFactory)
            :base(loggerFactory,memoryCache)
        {
            _userStorage = userStorage;
            _pointStrategyStorage = pointStrategyStorage;
            _userPointListStorage = userPointListStorage;
        }

        public void Handle(UserPointEvent e)
        {
            if(e.PointStrategyType== PointStrategyTypes.Unknow)
            {
                return;
            }
            var pointStrategy = _pointStrategyStorage.GetById(e.PointStrategyType.ToString());
            if (pointStrategy == null)
            {
                base.GetLogger.LogError($"userId：{e.UserId},{nameof(pointStrategy)}是空({e.PointStrategyType})");
                return;
            }

            var user = _userStorage.GetById(e.UserId);
            if (user == null)
            {
                base.GetLogger.LogError($"userId：{e.UserId},{nameof(user)}是null({e.PointStrategyType})");
                return;
            }

            user.IncreaseExp(pointStrategy.ExpPoints);
            user.IncreaseTradingPoint(pointStrategy.TradingPoints);

            _userStorage.Context.Commit();

            var point = new UserPointHistory
            {
                UserId = e.UserId,
                Exp = pointStrategy.ExpPoints,
                PointStrategyId = pointStrategy.Id,
                TradingPoints = pointStrategy.TradingPoints,
                Remark = $"{pointStrategy.Name}，经验 {pointStrategy.ExpPoints.GetPositiveNumString()}，金币 {pointStrategy.TradingPoints.GetPositiveNumString()}"
            };

            _userPointListStorage.Add(point);
            _userPointListStorage.Context.Commit();

            base.Cache.Set(UserPointHistory.GetUserPointCacheKey(e.UserId), point, DateTimeOffset.Now.AddSeconds(30));


        }
    }
}
